<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="分站">
              <a-input v-if="userInfo.userType == 3 || userInfo.userType == 2" disabled v-model="userInfoSite.name"></a-input>
              <a-input v-if="userInfo.userType == 1" placeholder="请输入分站名称" v-model="queryParam.siteName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="商家">
              <a-input v-if="userInfo.userType == 3" disabled v-model="userInfoMerchant.name"></a-input>
              <a-input v-if="userInfo.userType == 1 || userInfo.userType == 2" placeholder="请输入商家名称" v-model="queryParam.merchantName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="服务名称">
              <a-input placeholder="请输入服务名称" v-model="queryParam.name"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="服务类型">
                <j-multi-select-tag placeholder="请选择服务类型" dictCode="serve_type" v-model="queryParam.serveType"/>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="状态">
                <j-dict-select-tag placeholder="请选择状态" v-model="queryParam.status" dictCode="serve_status"/>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24" v-if="userInfo.userType == 1 || userInfo.userType == 2">
              <a-form-item label="商家手机号">
                <a-input placeholder="请输入商家手机号" v-model="queryParam.merchantMobile"></a-input>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" v-if="permissionData.serveAdd" type="primary" icon="plus">新增</a-button>
      <a-button @click="handleShop" v-if="permissionData.serveShop" icon="setting">店铺管理</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <span slot="status" slot-scope="text, record">
          <span v-if="permissionData.serveUpDown">
            <a-popconfirm :title="serveUpDownTagData[text].popconfirmTitle" @confirm="() => handleUpDown(record.id, text)">
              <a-tag class="mouse-hand" :color="serveUpDownTagData[text].color">{{serveUpDownTagData[text].text}}</a-tag>
            </a-popconfirm>
          </span>
          <span v-else>
            <a-tag :color="serveUpDownTagData[text].color">{{serveUpDownTagData[text].text}}</a-tag>
          </span>
        </span>

        <span slot="action" slot-scope="text, record">
          <span v-if="permissionData.serveEdit && permissionData.serveDelete">
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a-dropdown>
              <a class="ant-dropdown-link">更多<a-icon type="down" /></a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a @click="handleDetail(record)">详情</a>
                </a-menu-item>
                <a-menu-item v-if="permissionData.serveDelete" v-show="record.status == 0">
                  <a-popconfirm
                    title="确定删除吗?"
                    @confirm="() => handleBeforeVerifyDelete(record)">
                    <a>删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </span>
          <span v-else>
            <span v-if="permissionData.serveEdit">
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
            </span>
            <span v-else-if="permissionData.serveDelete">
              <a @click="handleBeforeVerifyDelete(record)">删除</a>
              <a-divider type="vertical" />
            </span>
            <a @click="handleDetail(record)">详情</a>
          </span>
        </span>

      </a-table>
    </div>

    <serve-modal ref="modalForm"  @ok="modalFormOk" />
    <serve-shop-modal ref="shopModalForm" :threeElements="threeElements" @ok="shopModalFormOk" />

  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import ServeModal from './modules/ServeModal'
  import ServeShopModal from './modules/ServeShopModal'
  import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
  import { upDownAction, getAction } from '@/api/manage'
  import { mapGetters } from 'vuex'
 import Vue from 'vue'
  import store from '@/store/'
  import { CURRENT_SHOP_INFO } from "@/store/mutation-types"

  export default {
    name: 'ServeList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {ServeModal, ServeShopModal},
    data () {
      return {
        description: '服务信息管理页面',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender: (text, row, index) => {
              return parseInt(index) + 1;
            }
          },
          {
            title:'服务名称',
            align:"center",
            dataIndex: 'name'
          },
          {
            title:'服务类型',
            align:"center",
            dataIndex: 'serveType_dictText'
          },
          {
            title:'状态',
            align:"center",
            dataIndex: 'status',
            scopedSlots: { customRender: 'status' },
          },
          {
            title:'门店',
            align:"center",
            dataIndex: 'shopId_dictText'
          },
          {
            title:'分站',
            align:"center",
            dataIndex: 'siteId_dictText'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          list: "/serve/list",
          delete: "/serve/delete",
          deleteBatch: "/serve/deleteBatch",
          putOnSale: "/serve/putOnSale",
          pullOffShelves: "/serve/pullOffShelves",
          shpoSelectOne: "/shop/shopBasic/selectOne"
        },
        dictOptions:{},
        serveUpDownTagData: {
          0: {
            color:"pink",
            text: "已下架",
            popconfirmTitle:"确定上架吗?"
          }, 1: {
            color:"green",
            text: "已上架",
            popconfirmTitle:"确定下架吗?"
          }
        },
        threeElements: null,
        // currentShop: null,
      }
    },
    created() {
      this.getShopOne()
    },
    computed: {
      ...mapGetters([
        "permissionData",
        "userInfo",
        "userInfoSite",
        "userInfoMerchant",
        "userInfoCurrentShop",
      ]),
    },
    methods: {
      getShopOne() {
        if (!this.permissionData.serveShop) return 
        getAction(this.url.shpoSelectOne, {}).then(res => {
          if (res.success) {
            this.currentShop = res.result
            Vue.ls.set(CURRENT_SHOP_INFO, this.currentShop, 7 * 24 * 60 * 60 * 1000)
            store.commit('CURRENT_SHOP_INFO', this.currentShop)
          }
        })
      },
      handleShop () {
        console.log(this.userInfoCurrentShop)
        // TODO 根据当前登录信息，判断是新增还是修改
        if (this.userInfo.userType == 3 && !this.userInfoCurrentShop) {
          this.$refs.shopModalForm.add();
          this.$refs.shopModalForm.title = "新增";
          this.$refs.shopModalForm.disableSubmit = false;
          this.threeElements = {
            site: this.userInfoSite ? this.userInfoSite['name'] : null,
            merchant: this.userInfoMerchant ? this.userInfoMerchant['name'] : null,
          }
        } else {
          this.$refs.shopModalForm.edit(this.userInfoCurrentShop);
          this.$refs.shopModalForm.title = "修改";
          this.$refs.shopModalForm.disableSubmit = false;
          this.threeElements = {
            site: this.userInfoSite.name,
            merchant: this.userInfoMerchant.name,
          }
        }
      },
      shopModalFormOk() {
        // TODO 触发更新前端门店缓存信息
        this.getShopOne()
      },
      handleUpDown(id, status){
        switch (status) {
          case 0: 
            return this.putOnSale(id)
          case 1:
            return this.pullOffShelves(id)
          default:
            return
        }
      },
      putOnSale(id) {
        let that = this;
        that.loading = true;
        upDownAction(that.url.putOnSale, {ids: id}).then((res) => {
          if (res.success) {
            //重新计算分页问题
            that.reCalculatePage(that.selectedRowKeys.length)
            that.$message.success(res.message);
            that.loadData();
            that.onClearSelected();
          } else {
            that.$message.warning(res.message);
          }
        }).finally(() => {
          that.loading = false;
        });
      },
      pullOffShelves(id) {
        let that = this;
        that.loading = true;
        upDownAction(that.url.pullOffShelves, {ids: id}).then((res) => {
          if (res.success) {
            //重新计算分页问题
            that.reCalculatePage(that.selectedRowKeys.length)
            that.$message.success(res.message);
            that.loadData();
            that.onClearSelected();
          } else {
            that.$message.warning(res.message);
          }
        }).finally(() => {
          that.loading = false;
        });
      },
      handleBeforeVerifyDelete(record) {
        if(record.status != 0) {
          this.$message.error("请下架后再删除!")
          return
        }
        this.handleDelete(record.id)
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>